//
//  PhotoPickerViewController.swift
//  SwiftWB
//
//  Created by 钟清 on 17/4/13.
//  Copyright © 2017年 Zhong Qing. All rights reserved.
//

import UIKit
import SVProgressHUD

class PhotoPickerViewController: UICollectionViewController {
    // MARK: - Property
    /* 数组：存储照片 */
    var images = [UIImage]()
    
    // MARK: - Life
    override func viewDidLoad() {
        super.viewDidLoad()
        
    }

    /* 数据源方法 */
    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return images.count + 1
    }
    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        /* 获取cell */
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier("photoPickerCell", forIndexPath: indexPath) as! PhotoPickerCollectionViewCell
        /* 赋值 */
        cell.delegate = self
        cell.image = (indexPath.item >= images.count) ? nil : images[indexPath.item]
        /* 返回cell */
        return cell
    }
}

// MARK: - Delegate
/* 照片处理 */
extension PhotoPickerViewController: PhotoPickerViewCellDelegate {
    /* 添加照片 */
    func photoPickerViewCellAddPhoto(cell: PhotoPickerCollectionViewCell) {
        /* 判断可用照片源 */
        guard UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.PhotoLibrary) else {
            SVProgressHUD.showErrorWithStatus("该照片源不可用")
            return
        }
        /* 照片选择控制器 */
        let pickerVC = UIImagePickerController()
        /* 照片源 */
        pickerVC.sourceType = .PhotoLibrary
        /* 代理 */
        pickerVC.delegate = self
        /* 弹出选择控制器 */
        presentViewController(pickerVC, animated: true, completion: nil)
    }
    /* 删除照片 */
    func photoPickerViewCellRemovePhoto(cell: PhotoPickerCollectionViewCell) {
        let indexPath = collectionView!.indexPathForCell(cell)!
        images.removeAtIndex(indexPath.item)
        collectionView?.reloadData()
    }
}
/* 选择照片 */
extension PhotoPickerViewController: UIImagePickerControllerDelegate,UINavigationControllerDelegate {
    func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
        let image = info["UIImagePickerControllerOriginalImage"] as! UIImage
        picker.dismissViewControllerAnimated(true, completion: nil)
        /* 压缩图片 */
        let newImage = drawImage(image, newImageWidth: 450)
        images.append(newImage)
        collectionView?.reloadData()
    }
    /* 绘图 */
    func drawImage(image: UIImage, newImageWidth: CGFloat) -> UIImage {
        let newImageHeight = (image.size.height / image.size.width) * newImageWidth
        let newImageSize = CGSize(width: newImageWidth, height: newImageHeight)
        UIGraphicsBeginImageContext(newImageSize)
        image.drawInRect(CGRect(x: 0, y: 0, width: newImageSize.width, height: newImageSize.height))
        let newImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return newImage
    }
}


// MARK: - Cell
@objc
protocol PhotoPickerViewCellDelegate: NSObjectProtocol {
    optional func photoPickerViewCellAddPhoto(cell: PhotoPickerCollectionViewCell)
    optional func photoPickerViewCellRemovePhoto(cell: PhotoPickerCollectionViewCell)
}
class PhotoPickerCollectionViewCell: UICollectionViewCell {
    /* 代理属性 */
    var delegate: PhotoPickerViewCellDelegate?
    /* 图片添加按钮 */
    @IBOutlet weak var photoAddButton: UIButton!
    /* 图片移除按钮 */
    @IBOutlet weak var photoRemoveButton: UIButton!
    /* 图片属性 */
    var image: UIImage? {
        didSet {
            if image == nil { // 没有选择图片
                photoAddButton.setBackgroundImage(UIImage(named: "compose_pic_add"), forState: UIControlState.Normal)
                photoAddButton.setBackgroundImage(UIImage(named: "compose_pic_add_highlighted"), forState: UIControlState.Highlighted)
                photoAddButton.userInteractionEnabled = true
                photoRemoveButton.hidden = true
            } else { // 有选中图片
                photoAddButton.setBackgroundImage(image, forState: UIControlState.Normal)
                photoAddButton.userInteractionEnabled = false
                photoRemoveButton.hidden = false
            }
        }
    }
    @IBAction func photoAddButtonClick() {
        if let tempDelegate = delegate {
            if tempDelegate.respondsToSelector(#selector(PhotoPickerViewCellDelegate.photoPickerViewCellAddPhoto(_:))) {
                tempDelegate.photoPickerViewCellAddPhoto!(self)
            }
            
        }
    }

    @IBAction func photoRemoveButtonClick() {
        if let tempDelegate = delegate {
            if tempDelegate.respondsToSelector(#selector(PhotoPickerViewCellDelegate.photoPickerViewCellRemovePhoto(_:))) {
                tempDelegate.photoPickerViewCellRemovePhoto!(self)
            }
        }
    }
    
    
}
// MARK: - Layout
class PhotoPickerCollectionViewLayout: UICollectionViewFlowLayout {
    override func prepareLayout() {
        super.prepareLayout()
        let margin: CGFloat = 10
        let col: CGFloat = 3
        let itemWH = ((collectionView?.bounds.width)! - (col + 1) * margin) / col
        itemSize = CGSize(width: itemWH, height: itemWH)
        minimumLineSpacing = 10
        minimumInteritemSpacing = 10
        sectionInset = UIEdgeInsets(top: margin, left: margin, bottom: 0, right: margin)
    }
}
